
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:flutter_im_demo/utils.dart';

import 'socket/frame_parser.dart';

const HOST = "192.168.0.113";
const PORT = 9092;
Socket socket;

void main() async {
  try {
    socket = await Socket.connect(HOST, PORT, timeout: Duration(seconds: 3));
    print("socket连接成功");

    _writeMsg();

    Timer.periodic(Duration(seconds: 5), (t) {
      _writeMsg();
    });
  } catch (e) {
    print("连接错误， $e");
  }

  socket.listen((onData) => onDataFun(onData, (msg) {
    print("收到：" + msg);
  }), onError: errorHandler, onDone: doneHandler, cancelOnError: false);
}

int count = 0;
void _writeMsg() {
  final random = Random();
  final map = {
    "id" : count++,
    "msg" : "helloworld${random.nextBool() ? "\r\n" : "NO"}"
  };
  String msg = json.encode(map);
  print("send msg: $msg");
  socket.write(stringToBase64(msg) + messageEnd);
}

void close() {
  socket?.close();
}

void doneHandler() {
  print("结束链接");
}

errorHandler(error) {
  print("监听出错，$error");
}